import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import materialreqbillsApi from '../../../common/api/cbs/materialreqbills.api.js'
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
import doT from '../../../../vendor/template/doT.js';
import { Select2Page } from "../../../common/serve-request.js";
import { multiplication, division } from '../../../../js/common/accuracy-calculation/index.js';

(function (window, document, $) {
    let _vm, getEntryInfo = [], pigDetails = [], pigDetailsInfo = []
    const PartnerSvcUrl = Utils.CurDomain.PartnerSvcUrl;
    const addsaleTemplate = doT.template($('#addpigType-template').text());

    $(function () {
        _vm = new Vue({
            el: "#recevEntries-form",
            data() {
                return {
                    entries: [
                        {
                            "seq": 0,
                            "material": {
                                "id": "",
                                "name": "",
                                "code": "",
                                "baseUnit": ""
                            },
                            "qty": '',
                            "materGroupName": '',
                            "price": '',
                            "amount": ''
                        }
                    ],
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
                if (params.isEdit == 'true') {
                    document.title = '入圈登记收货分录 - 编辑'
                }
            },
            methods: {
                // 保存
                submit() {
                    let { material, qty, price, amount } = _vm.entries[0]
                    if (!Utils.IsNotNull(material.id)) {
                        return $.toptip(`请选择物料!`, 'warning');
                    }
                    if (qty==null||qty==undefined||qty=='') {
                        return $.toptip(`请输入领用数量!`, 'warning');
                    }
                    if (!Utils.IsNotNull(price)) {
                        return $.toptip(`请输入领用单价!`, 'warning');
                    }
                    if (!(/(^[0-9]\d*$)/.test(qty))) {
                        return $.toptip(`头数为整数!`, 'warning');
                    }
                    if (!(/^(?!0+(?:\.0+)?$)(?:[0-9]\d*|0)(?:\.\d{1,2})?$/.test(price))) {
                        return $.toptip(`单价必须大于等于0并且只能保留两位小数!`, 'warning');
                    }
                    savetips({ ..._vm.entries[0] })
                }
            }
        });
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        _initCommand();

    });

    // 初始化数据
    const _initCommand = async () => {
        getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo")) || []
        let isEdit = JSON.parse(getUrlKey('isEdit'))
        let seqId = getUrlKey('index')        
        //物料
        _select2Material('materialId');
        $(`#materialId`).on('select2:select', function (e) {
            _vm.entries[0].material.id = $(this).val();
            _vm.entries[0].material.name = $(this).select2('data')[0].text;
            _vm.entries[0].material.code = $(this).select2('data')[0].numCode;
            _vm.entries[0].material.baseUnit = $(this).select2('data')[0].baseMeasureUnit;
            _vm.entries[0].materGroupName = $(this).select2('data')[0].groupName;
            let data = e.params.data; // 获取选中项的数据
            let text = data.text; // 获取选中项的文本
            let saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
        });
        // 编辑时赋值
        if (isEdit) {
            let datas = getEntryInfo.find(item => item.seq == seqId)
            const propertiesToCopy = ["material","qty","materGroupName","price","amount"];
            propertiesToCopy.reduce((obj, prop) => {
                _vm.entries[0][prop] = datas[prop];
            }, {});
            $(`#materialId`).setSelectValue(_vm.entries[0].material.id, cutstr(_vm.entries[0].material.name, 20));
        }

        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../materialreqbills/addmaterialreqbills.html?v=${Utils.GetTime()}`;
        });

        // 领用单价改变计算领用金额
        $(document).on('change', '#price', function () {
            let price = Number(_vm.entries[0].price);
            let qty = Number(_vm.entries[0].qty);
            if(price && qty){
                _vm.entries[0].amount = multiplication(price, qty);
            }else{
                _vm.entries[0].amount = 0;
            }
        })

        // 领用数量改变计算领用金额
        $(document).on('change', '#qty', function () {
            let price = Number(_vm.entries[0].price);
            let qty = Number(_vm.entries[0].qty);
            if(price && qty){
                _vm.entries[0].amount = multiplication(price, qty);
            }else{
                _vm.entries[0].amount = 0;
            }
        })

    }

    // 保存提示
    const savetips = (data) => {
        let savetype
        if (Utils.IsNotNull(getUrlKey("isEdit"))) {
            savetype = '修改'
        }
        else {
            savetype = '保存'
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
    				<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
    					<div>是否确认${savetype}该分录？</div>
    				</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        let seq = parseInt(getUrlKey('index'))
                        let isEdit = JSON.parse(getUrlKey('isEdit'))
                        // 新增
                        if (!isEdit) {
                            getEntryInfo.push(data)
                        }
                        // 编辑
                        else if (isEdit) {
                            getEntryInfo[seq] = data
                        }
                        getEntryInfo.map((item, index) => {
                            item.seq = index
                        })
                        // 存入SessionStorage
                        JSON.stringify(Utils.SetSessionStorage("getEntryInfo", getEntryInfo))
                        location.href = `./addmaterialreqbills.html?v=${Utils.GetTime()}`;
                        $.closeModal();
                    }
                }
            ]
        });
    }

    // 获取地址栏的参数
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }

    //查询物料信息
    const _select2Material = (id) => {
        Select2Page($(`#${id}`), `${Utils.CurDomain.MasterDataUrl}/yymaterials/q`, (params) => {
            return ({
                mgroupid: 'SAP-1',
                // searchinfo: params.term,
                pagesize: 10,
                pageindex: (params.page || 1) - 1,
                ...(Utils.IsNotNull(params.term) ? { searchinfo: params.term } : {})
            })
        }, "GET", {
            allowClear: true,//允许清空
            placeholder: '请选择物料...', //默认文字提示
            templateResult: function (res) {
                // _entriesMatrls = [{ id: "", text: "请选择物料..." }];
                if (Utils.IsNotNull(res.id)) {
                    let sltHtml = {
                        id: res.id,
                        text: res.name,
                        name: res.name,
                        numCode: res.numCode,
                        baseMeasureUnit: res.baseMeasureUnit,
                        subMeasureUnit: res.subMeasureUnit,
                        textString: res.name + "," + res.numCode + "," + res.model + "," + res.baseMeasureUnit,
                        ...res
                    }
                    let sltSpanHtml = "";
                    if (!res.id) {
                        return "";
                    }
                    let arr = sltHtml?.textString?.split(',');
                    if (!arr) return;
                    res.id == -1 ? "" : sltSpanHtml +=
                        `<div style='margin-bottom: 8px;color:#000'>${arr[0]}</div>
                    <label style='font-size:0'>
                    <span style="border: #3e8ef7 1px solid;background-color: #fff;padding : 2px 4px;color:#3e8ef7;font-size: 9px;border-radius: 10px 0 0 10px">${arr[1]}</span>
                    <span style="border: #8A5082 1px solid;background-color: #8A5082;; padding : 2px 4px;color:#fff;font-size: 9px;">${arr[2]}</span>
                    <span style="border: #758EB7 1px solid;background-color: #758EB7;; padding : 2px 4px;color:#fff;font-size: 9px;border-radius: 0 10px 10px 0;">${arr[3]}</span>
                    </label>`;
                    return $(`<span data-code = "${arr[1]}" data-name="${arr[0]}" data-model = "${arr[2]}" data-unit = "${arr[3]}">${sltSpanHtml}</span>`);
                }
            }
        });
        $(`#${id}`).setSelectValue();
    }


})(window, document, jQuery)